package com.zhuoyue.common.aop.param;


import com.zhuoyue.common.exception.ErrorType;
import com.zhuoyue.common.exception.ZyServerException;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * 参数为空判断
 *
 * @author hewenze
 */
@Aspect
@Component
public class ParamsAspect {

    @Before("@annotation(com.zhuoyue.common.aop.param.Params)")
    public void paramAspect(JoinPoint point) throws Exception {
        System.out.println("参数不能为空");
        // 获取方法签名
        MethodSignature methodSignature = (MethodSignature) point.getSignature();
        // 获取方法
        Method method = methodSignature.getMethod();
        Params paramsTake = method.getAnnotation(Params.class);
        // 获取操作描述的属性值
        String value = paramsTake.requestParamsValue();
        String name = paramsTake.requestParamsName();
        if (StringUtils.isNotEmpty(value)) {
            String[] values = StringUtils.split(value, ",");
            String[] names = StringUtils.split(name, ",");
            HttpServletRequest request = getHttpServletRequest();
            for (int i = 0; i < values.length; i++) {
                String parameter = request.getParameter(values[i]);
                if (StringUtils.isEmpty(parameter)) {
                    if (names.length > 0) {
                        throw new ZyServerException(ErrorType.OBJECT_NOT_FOUND.getCode(), names[i] + "不能为空");
                    } else {
                        throw new ZyServerException(ErrorType.OBJECT_NOT_FOUND);
                    }

                }
            }
        }
    }


    private HttpServletRequest getHttpServletRequest() {
        //1.从header里面获取token
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes attributes = (ServletRequestAttributes) requestAttributes;
        return attributes.getRequest();
    }

}


